<?php
class Fonts extends Model_Abstract
{
	public $tableName = 'fonts';
	
	protected $_previewImg_fontSize = 12;
	protected $_previewImg_fontColor = 'rgb(0, 0, 0)';
	protected $_previewImg_bg = 'rgb(243, 251, 254)';

	
	protected $_validation = array(
		'name' => array(
			array('max_length', '字体名称长度不能超过100', 100),
			array('not_empty', '请填写字体名称')
		),
		'default_preview_string' => array(
			array('max_length', '默认预览字符串长度不能超过200', 200),
			array('not_empty', '请填写默认预览字符串')
		),
		'root_foldername' => array(
			array('max_length', '资源路径最长100个字符', 100),
		),
		'sketch' => array(
			array('max_length', '请在500个字以内描述模板', 500),
		),
		'font_file' => array(
			array('max_length', '字体文件名最长50个字符', 50),
		),
		'download_pack' => array(
			array('max_length', '下载包文件名最长50个字符', 50),
		),
		'view_num' => array(
			array('is_int', 'view_num必须是数字'),
		),
	);
	
	public function init()
	{
		$this->initAttributes();
	}
	
	public static function model($classname = __CLASS__)
	{
		return parent::model($classname);
	}
	
	public function attributeLabels()
	{
	}
	
	public function getAll()
	{
		$sql = " SELECT 
					jq.*, 
					jq_t.name type, jq_t.name_en type_en 
				FROM 
					jqueryplugins jq 
				LEFT JOIN 
					jqueryplugins_type jq_t ON jq.type_id = jq_t.id ";

		return $this->_connection->query($sql);
	}
	
	public function paginationGetAll($page, $type_id)
	{
		$perPage = JQUERYPLUGINS_LIST_PERPAGE;
		$limit = " LIMIT " .($page-1)*$perPage . ", {$perPage}";
		
		$sqlWhere = '';
		$query = array();
		$vars = array();
		if(!empty($type_id)){
			$query[] = ' type_id = ? ';
			$vars[] = $type_id;
		}
		$sqlWhere = ' WHERE ' . implode(' AND ', $query);
		
		$sqlCount = " SELECT COUNT(*) total_num FROM jqueryplugins " . $sqlWhere;
		$result = $this->_connection->query($sqlCount, $vars);
		$totalCount = $result[0]['total_num'];
		
		$sql = " SELECT 
					jq.*, 
					jqueryplugins_type.name type_name, jqueryplugins_type.name_en type_name_en 
				FROM 
					jqueryplugins jq 
				LEFT JOIN 
					jqueryplugins_type ON jq.type_id = jqueryplugins_type.id ";
		
		$sql .= $sqlWhere . $limit;
		$result = $this->_connection->query($sql, $vars);
		foreach($result as $k => $r){
			$result[$k] = $this->replaceDescriptionVars($r);
		}
		
		$result['totalCount'] = $totalCount;
		return $result;
	}
	
	public function initAttributes()
	{
		$this->attributes = array(
				'name' => '',
				'sketch' => '',
				'default_preview_string' => '',
				'root_foldername' => '',
				'font_file' => '',
				'download_pack' => '',
				'type_using_id' => '',
				'type_area_id' => '',
				'type_feature_id' => '',
				'view_num' => '',
				'download_num' => '',
				'recommend' => '',
				'created_date' => '',
				'created_int' => ''
		);
	}
	
	public function mergeTypeWithId($types, $fonts)
	{
		foreach($fonts as $k => $font){
			$fonts[$k]['type_using_name'] = '';
			$fonts[$k]['type_using_name_en'] = '';
			$fonts[$k]['type_area_name'] = '';
			$fonts[$k]['type_area_name_en'] = '';
			$fonts[$k]['type_feature_name'] = '';
			$fonts[$k]['type_feature_name_en'] = '';
	
			if(!empty($types[$font['type_using_id']])){
				$fonts[$k]['type_using_name'] = $types[$font['type_using_id']]['name'];
				$fonts[$k]['type_using_name_en'] = $types[$font['type_using_id']]['name_en'];
			}
			if(!empty($types[$font['type_area_id']])){
				$fonts[$k]['type_area_name'] = $types[$font['type_area_id']]['name'];
				$fonts[$k]['type_area_name_en'] = $types[$font['type_area_id']]['name_en'];
			}
			if(!empty($types[$font['type_feature_id']])){
				$fonts[$k]['type_feature_name'] = $types[$font['type_feature_id']]['name'];
				$fonts[$k]['type_feature_name_en'] = $types[$font['type_feature_id']]['name_en'];
			}
		}
		return $fonts;
	}
	
	protected function _find($fields = '*', $attributes = array(), $constraint = array(), $conditions = array(), $params = array())
	{
		$result = parent::_find($fields, $attributes, $constraint, $conditions, $params);
		$c = array_merge(
			$this->_constraintFind,
			array('mergeType' => false),
			$constraint
		);
		extract($c);
		if($mergeType){
			$types = Types::model()->find('*', array('tablename' => 'fonts'), array('setResultKey' => 'id'));
			$result = $this->mergeTypeWithId($types, $result);
		}
		
		return $result;
	}

	public function saveFiles($fileInfos)
	{
		$root = FONTS_DIR . '/' . $this->attributes['root_foldername'];
		@mkdir($root, 0777, true);
		
		$ret = true;
		if(!empty($fileInfos['name']['font_file'])){
			$font_file = $this->attributes['font_file'];
			$tmpName = $fileInfos['tmp_name']['font_file'];
			
			$ret = copy($tmpName, $root . '/' . $font_file);
		}
		if(!empty($fileInfos['name']['download_pack'])){
			$download_pack = $this->attributes['download_pack'];
			$tmpName = $fileInfos['tmp_name']['download_pack'];
			
			$ret = copy($tmpName, $root . '/' . $download_pack);
		}
		
		return $ret;
	}

	
	public function printStringImg($fontSize = null, $string = null)
	{
		$string = '你好';
// 		$string = mb_convert_encoding($string, "utf-8", "GB2312");
// 		$string = utf8_encode($string);
// 		$string = utf8_decode($string);
		$cmd = '
			convert c:\1.png -transparent white -font c:\simfang.ttf -fill black -pointsize 24 -draw "text 5, 25 \''.$string.'\'" c:\3.png
		';fdump($cmd);
		exec($cmd, $out, $result);
		
		
		fdump($out);
		fdump($result);
		exit();
		die();
		
		
		error_reporting(0);
		
		if($fontSize === null){
			$fontSize = $this->_previewImg_fontSize;
		}
		if($string === null){
			$string = $this->attributes['default_preview_string'];
		}
 		$string = "*aaaaaaaaaaaaaq\nbaaaaa\nddd\nasdasdasdasd 娃哈哈";
		
		$lineNum = substr_count($string, "\n") + 1;
		$maxLineLen = 0;
		$lines = explode("\n", $string);
		foreach($lines as $l){
			if(strlen($l) > $maxLineLen){
				$maxLineLen = strlen($l);
			}
		}
		$imageL = $fontSize * $maxLineLen;
		$imageH = $fontSize * 2 * $lineNum;

		$ttf = FONTS_DIR . '/' . $this->attributes['root_foldername'] . '/' . '1.ttf';//$this->attributes['font_file'];


		$image = new Imagick();
		$image->newImage(
			$imageL, 
			$imageH, 
			new ImagickPixel($this->_previewImg_bg)
		);
		
		$draw = new ImagickDraw();
// 		$draw->setTextEncoding('utf-8');
		$draw->setFillColor(new ImagickPixel($this->_previewImg_fontColor));
		$draw->setFont($ttf);
		$draw->setFontSize($fontSize);
		$string = mb_convert_encoding($string, "utf-8", array("GB2312", "big5"));
// 		$string = utf8_encode($string);
// 		$string = utf8_decode($string);
		$image->annotateImage($draw, $fontSize, $fontSize * 2, 0, $string);
		$image->setImageFormat('png');
		header('Content-type: image/png');
		echo $image;
		
	}
	
	protected function _delete($deleteFiles = false, $attributes = array(), $conditions = array(), $params = array())
	{
		if($deleteFiles){
			$root = $this->find('root_foldername', $attributes, array('onlyOne' => true, 'stripName' => true), $conditions, $params);
			$root = FONTS_DIR . '/' . $root;
			@mkdir($root, 0777, true);
			Util::removePath($root);
		}
		$this->_before_sql();
		return parent::_delete($attributes, $conditions, $params);
	}
	
}